import st7789
import time
import gc
import struct
from queue import Queue
from machine import SPI,Pin,UART
import socket

spi = SPI(1, baudrate=40000000, polarity=1, sck=Pin(10), mosi=Pin(8))
tft = st7789.ST7789(spi, 240,320, reset=Pin(6, Pin.OUT), dc=Pin(4, Pin.OUT),cs=Pin(2, Pin.OUT),backlight=Pin(1, Pin.OUT), inversion=True,color_order=st7789.RGB ,rotation=1)


tft.init()

tft.fill(st7789.BLACK)

#务必联网
# wlan=network.WLAN(network.STA_IF)
# wlan.active(True)
# # wlan.disconnect()
# wlan.connect("ppp","12345678")
# print(wlan.ifconfig(),gc.mem_free())


host='192.168.253.5'
port=9010
sa=socket.socket()
sa.bind((host,port))
sa.listen(5)

print(gc.mem_free())
b=b''
tt=0
while True:
    s,a=sa.accept()
    while True:
        try:
            c=time.ticks_ms()
            m=s.recv(10000)
            b=b+m
            tt=tt+1
            ed=time.ticks_ms()
            if len(b)>=88480:
                tft.blit_buffer(b[0:88480],20,40,280,158)
                b=b[88480:]
                ta=tt*(ed-c)+time.ticks_ms()-ed
                print("end:",gc.mem_free(),ta)
                
#                 time.sleep_ms(150-ta)
#                 time.sleep_ms(150-(tt*(ed-c)+time.ticks_ms()-ed))
                tt=0
            gc.collect()
        #print(gc.mem_free())
        except Exception as e:
            s.close()
            print("close tcp")
    
#ffmpeg -f gdigrab -i desktop -r 3 -vf scale=280:158 -f rawvideo -pix_fmt rgb565be tcp://192.168.253.5:9010



